package com.harmontronics.hanma.paas.paas.domain.iam.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.harmontronics.hanma.paas.paas.domain.iam.entity.PermAction;
import com.harmontronics.hanma.paas.paas.domain.iam.entity.PermActionList;
import com.harmontronics.hanma.paas.paas.domain.iam.service.HmRolePermActionService;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.valueobject.Constants;
import com.harmontronics.hanma.paas.paas.domain.iam.entity.valueobject.HmRolePermFields;
import com.harmontronics.hanma.paas.paas.domain.iam.repository.persistence.HmRolePermRepository;
import com.harmontronics.hanma.paas.paas.domain.iam.entity.HmRolePerm;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.harmontronics.hanma.paas.paas.common.PageBase;

import com.harmontronics.hanma.paas.paas.domain.iam.repository.mapper.HmRolePermMapper;
import com.harmontronics.hanma.paas.paas.domain.iam.repository.po.HmRolePermPO;
import java.util.List;

@Service("hmRolePermService")
@DS("#header.App-Unique")
public class HmRolePermService{

    @Autowired
    private HmRolePermRepository hmRolePermRepository;

    @Autowired
    private HmRolePermMapper hmRolePermMapper;

    @Autowired
    private HmRolePermActionService hmRolePermActionService;


    public HmRolePerm findById( Integer id){
            HmRolePermPO po =   hmRolePermRepository.getById(id);
        return BeanUtil.toBean(po,HmRolePerm.class);
    }

    public void save(HmRolePerm hmRolePerm){
            HmRolePermPO po =  BeanUtil.toBean(hmRolePerm,HmRolePermPO.class);
            hmRolePermRepository.save(po);
    }

    public void update(HmRolePerm hmRolePerm){
            HmRolePermPO po =  BeanUtil.toBean(hmRolePerm,HmRolePermPO.class);
            hmRolePermRepository.updateById(po);
    }

    public void remove(List<Integer> ids){
            hmRolePermRepository.removeByIds(ids);
    }

    public List<HmRolePerm> getList(){
        List<HmRolePermPO> pos =  hmRolePermRepository.list();
        return Convert.toList(HmRolePerm.class,pos) ;
    }

    public PageBase<HmRolePerm> getList(int pageNo,int pageSize){
        Page<HmRolePermPO> page = new Page<>(pageNo, pageSize);
        IPage<HmRolePermPO> resultPage =
                    hmRolePermRepository.selectPage(Wrappers.emptyWrapper(),page);
        return PageBase.from(resultPage,HmRolePerm.class);
    }


    public List<PermActionList> selectCurrentPermAction(Long roleId) {
        return hmRolePermMapper.selectPermActionWithRoleId(roleId);
    }

    /**
     * 写入当前角色的权限
     *
     * @param roleId
     * @param permissions
     */
    public void insertRolePermAction(Long roleId, List<PermActionList> permissions) {
        for (PermActionList permission : permissions) {
            if (CollectionUtils.isNotEmpty(permission.getChildren())) {
                HmRolePermPO rolePerm = new HmRolePermPO().setRoleId(roleId).setPermId(permission.getId());
                for (PermAction child : permission.getChildren()) {
                    if (CollectionUtils.isNotEmpty(child.getChildren()) || CollectionUtils
                            .isNotEmpty(child.getActions())) {

                        HmRolePermPO childPerm = new HmRolePermPO().setRoleId(roleId)
                                .setPermId(child.getId());

                        if (child.getChildren() != null) {
                            for (PermAction grandson : child.getChildren()) {
                                if (CollectionUtils.isNotEmpty(grandson.getActions())) {
                                    HmRolePermPO grandsonPerm = new HmRolePermPO().setRoleId(roleId)
                                            .setPermId(grandson.getId());
                                    hmRolePermRepository.save(grandsonPerm);
                                    if (childPerm.getId() == null) {
                                        hmRolePermRepository.save(childPerm);
                                    }
                                    if (rolePerm.getId() == null) {
                                        hmRolePermRepository.save(rolePerm);
                                    }
                                    hmRolePermActionService
                                            .parseActions(grandson.getActions(),
                                                    grandsonPerm.getId());
                                } else if (grandson.getMeta() != null) {
                                    JSONObject metaObject = JSONUtil.parseObj(grandson.getMeta());
                                    if (metaObject.getBool(Constants.HIDDEN)) {
                                        HmRolePermPO hiddenRolePerm = new HmRolePermPO().setRoleId(roleId)
                                                .setPermId(grandson.getId());
                                        hmRolePermRepository.save(hiddenRolePerm);
                                    }
                                }
                            }
                        }
                        if (CollectionUtils.isNotEmpty(child.getActions())) {
                            if (childPerm.getId() == null) {
                                hmRolePermRepository.save(childPerm);
                            }
                            if (rolePerm.getId() == null) {
                                hmRolePermRepository.save(rolePerm);
                            }
                            hmRolePermActionService
                                    .parseActions(child.getActions(), childPerm.getId());
                        }
                    }
                    // 还有隐藏菜单需要处理
                    if (child.getMeta() != null) {
                        JSONObject metaObject = JSONUtil.parseObj(child.getMeta());
                        if (metaObject.containsKey(Constants.HIDDEN) && metaObject
                                .getBool(Constants.HIDDEN)) {
                            HmRolePermPO hiddenRolePerm = new HmRolePermPO().setRoleId(roleId)
                                    .setPermId(child.getId());
                            hmRolePermRepository.save(hiddenRolePerm);
                        }
                    }
                }
            }
        }
    }


    /**
     * 更新现有的权限
     *
     * @param roleId
     * @param permissions
     */
    public void updateRolePermAction(Long roleId, List<PermActionList> permissions) {
        // 根据roleId删除现有的权限
        // 1.先查询出所有的rolePermId
        List<Long> rolePermIds = hmRolePermMapper.selectRolePermIds(roleId);
        // 2.根据rolePermId删除RolePermAction表中的数据
        hmRolePermActionService.deleteWithRolePermIds(rolePermIds);
        // 3.删除RolePerm表中的数据
        hmRolePermMapper.delete(
                new UpdateWrapper<HmRolePermPO>().eq(HmRolePermFields.ROLE_ID, roleId));

        // 重新写入文件
        insertRolePermAction(roleId, permissions);
    }

}